package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.convention.exception.ServiceException;
import com.example.demo.dao.entity.Account;
import com.example.demo.dao.mapper.AccountMapper;
import com.example.demo.dto.request.UserRegisterReq;
import com.example.demo.service.AccountService;

import com.example.demo.utils.Const;
import jakarta.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import static com.example.demo.common.convention.errorcode.BaseErrorCode.USER_NAME_EXIST_ERROR;

/**
 * 账户信息处理相关服务
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Resource
    PasswordEncoder passwordEncoder;
    /**
     * 从数据库中通过用户名或邮箱查找用户详细信息
     * @param username 用户名
     * @return 用户详细信息
     * @throws UsernameNotFoundException 如果用户未找到则抛出此异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = this.findAccountByUserName(username);
        if(account == null)
            throw new UsernameNotFoundException("用户名或密码错误");
        return User
                .withUsername(username)
                .password(account.getPassword())
                .roles(account.getRole())
                .build();
    }

    @Override
    public Account findAccountByUserName(String username) {
        QueryWrapper<Account> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public void register(UserRegisterReq req){
        String username = req.getUsername();
        if(this.findAccountByUserName(username)!=null) throw new ServiceException(USER_NAME_EXIST_ERROR);
        String password = passwordEncoder.encode(req.getPassword());
        Account account = new Account(null, req.getUsername(),
                password, Const.ROLE_DEFAULT);
        this.save(account);
    }
}
